#include "my_stdio.h"
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <malloc.h>
#include <assert.h>

my_file* my_fopen(const char* _str,const char* _mode)
{
  int flag = 0;
  size_t fd=0;
  if(strcmp(_mode,"w") ==0) flag |= (O_CREAT | O_WRONLY | O_TRUNC);
  else if(strcmp(_mode,"r") == 0) flag |= O_RDONLY;
  else if(strcmp(_mode,"a") ==0) flag |= (O_CREAT | O_WRONLY | O_APPEND);
  mode_t mode = 0666;
  if(flag == 0) return NULL;
  if(flag & O_RDONLY) fd = open(_str,flag);
  else fd = open(_str,flag,mode);
  my_file* file = (my_file*)malloc(sizeof(my_file));
  if(file == NULL) 
  {
    close(fd);
    return NULL;
  };

  file->current =0;
  file->fd  = fd;
  file->flag |= BUFF_LINE;
  memset(file->buffer,'\0',NUM);
  return file;
}

int my_fclose(my_file* file)
{
  if(file->current == NUM) my_fflush(file);
  assert(file);
  close(file->fd);
  file = NULL;

  return 1;
}

int my_fwrite(const void* _str,size_t size,size_t nmenb,my_file* file)
{
  assert(file);
  if(file->current == NUM) my_fflush(file);
  size_t input_size = size * nmenb;
  size_t writen =0;
  size_t user_size = file->current;
  if(NUM - file->current >= input_size)
  {
    memcpy(file->buffer+file->current,_str,input_size);
    file->current += input_size;
    writen = input_size;
  }
  else 
  {
    memcpy(file->buffer+file->current,_str,NUM-file->current);
    file->current = NUM;
    writen = NUM - user_size;
  }
  printf("%lu %lu\n",size,nmenb);
  if(file->flag & BUFF_LINE && file->buffer[file->current-1] == '\n')  my_fflush(file);
  else if(file->current == NUM) my_fflush(file);

  return writen;
}


int my_fflush(my_file* file)
{
  assert(file);
  write(file->fd,file->buffer,file->current);
  file->current=0;

  return 1;
}
